/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.context;

import java.util.Map;
import java.util.HashMap;

/**
 * Immutable implementation of {@link org.aspectsense.context.ContextType}. The
 * construction is done through the use of the factory pattern, where a static
 * cache is available and a new instance is created only when not present in
 * the cache already.
 *
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 *         Date: Jan 2, 2008
 *         Time: 2:59:54 PM
 */
public class DefaultContextType implements ContextType
{
    public static final ContextType ROOT_CONTEXT_TYPE
            = getContextType("context");

    public static final ContextType USER_PREFERENCES_CONTEXT_TYPE
            = getContextType("context.user.preferences");

    public static final ContextType COMPONENT_AVAILABILITY_CONTEXT_TYPE
            = getContextType("context.infrastructure.component-availability");

    public static final ContextType SERVICE_AVAILABILITY_CONTEXT_TYPE
            = getContextType("context.infrastructure.service-availability");

    private final String type;

    private static Map<String, ContextType> cachedContextTypes = null;

    static private Map<String, ContextType> getCachedContextTypes()
    {
        if(cachedContextTypes == null)
        {
            cachedContextTypes = new HashMap<String, ContextType>();
        }

        return cachedContextTypes;
    }

    static ContextType getContextType(final ContextType parent, final String type)
    {
        if(type == null)
        {
            throw new NullPointerException("Illegal null argument");
        }

        if(!isValidContextType(type))
        {
            throw new IllegalArgumentException("Invalid format of context type: " + type);
        }

        return getContextType(parent.getType() + "." + type);
    }

    static ContextType getContextType(final String type)
    {
        synchronized (DefaultContextType.class)
        {
            if(getCachedContextTypes().containsKey(type))
            {
                return getCachedContextTypes().get(type);
            }

            final ContextType contextType = new DefaultContextType(type);
            getCachedContextTypes().put(type, contextType);
            return contextType;
        }
    }

    private DefaultContextType(final String type)
    {
        this.type = type;
    }

    public String getType()
    {
        return type;
    }

    public boolean isChildOf(final ContextType prospectiveAncestor)
    {
        return type.startsWith(prospectiveAncestor.getType());
    }

    public String toString()
    {
        return type;
    }

    public int hashCode()
    {
        return type.hashCode();
    }

    public boolean equals(final Object otherObject)
    {
        if(otherObject == null) return false;

        if(this == otherObject) return true;

        if(otherObject.getClass() != this.getClass()) return false;

        final String otherType = ((DefaultContextType) otherObject).type;

        return this.type.equals(otherType);
    }

    private static boolean isValidContextType(final String type)
    {
        final char [] charArray = type.toCharArray();
        for(final char c : charArray)
        {
            if(!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '_'))
            {
                return false;
            }
        }

        return true;
    }
}